import decimal

from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, QueryDict
from CarManage.models import *
from CarManage.serializers import *

# Create your views here.


@csrf_exempt
def getCars(request):
    if request.method == 'GET':
        print("GET")
        manager = request.GET.get('id')
        now = request.GET.get('WorkingState')
        if now is not None:
            car_list = Car.objects.filter(ManagerID=manager, WorkingState=now)
        else:
            car_list = Car.objects.filter(ManagerID=manager)
        cars = []
        for car in car_list:
            cars.append(car.to_dict())
        return JsonResponse({'Cars': cars}, safe=False)

@csrf_exempt
def modifyCar(request):
    if request.method == 'POST':
        print(request.POST)
        try:
            car = Car.objects.get(CarID=request.POST.get("CarID"))
        except Car.DoesNotExist:
            return JsonResponse({"Message": "Car Does Not Exist"}, safe=False)
        car = CarSerializer(car,request.POST)
        if car.is_valid():
            car.save()
            return JsonResponse({"Message": "Success"}, safe=False)
        else:
            print(car.errors)
            return JsonResponse({"Message": "Arguments Illegal"}, safe=False)


@csrf_exempt
def addNewCar(request):
    if request.method == 'POST':
        result = Car.objects.filter(CarID=request.POST.get("CarID"))
        data=request.POST.copy()
        if data["PassengerNum"] is None:
            if data["CarCategory"] == "大型车":
                data["PassengerNum"] = 40
            elif data["CarCategory"] == "中型车":
                data["PassengerNum"] = 15
            if data["CarCategory"] == "小型车":
                data["PassengerNum"] = 8
        if result.exists():
            return JsonResponse({'Message': "CarId Exists"}, safe=False)
        car = CarSerializer(data=data)
        if car.is_valid():
            car.save()
        else:
            return JsonResponse({"Message": "Arguments Illegal"}, safe=False)
        return JsonResponse({"Message": "Success"}, safe=False)


@csrf_exempt
def changeWorkingState(request):
    if request.method == 'POST':
        car = None
        try:
            car = Car.objects.get(CarID=request.POST.get("CarID"))
        except Car.DoesNotExist:
            return JsonResponse({"Message": "Car Does Not Exist"}, safe=False)
        ws = request.POST.get("WorkingState")
        car_data = {"WorkingState": ws}
        record_data = {}
        if ws == car.WorkingState:
            return JsonResponse({"Message": "No need to change"}, safe=False)
        if ws == "停用":
            if car.WorkingState == "维修":
                record = Repair.objects.filter(Car=car, EndTime=None)
                record_data["EndTime"] = timezone.localdate()
                for i in record:
                    j = RepairSerializer(i, data=record_data)
                    if j.is_valid():
                        j.save()
            else:
                car_data["StopUseReason"] = request.POST.get("Reason")
                car_data["StopServeDate"] = timezone.localdate()
            car = CarSerializer(car, data=car_data)
        elif ws == "可用":
            car = CarSerializer(car, data=car_data)
        elif ws == "维修":
            record_data["Reason"] = request.POST.get("Reason")
            record_data["StartTime"] = timezone.localdate()
            print(car.to_dict())
            record_data["Car"] = car.CarID
            record = RepairSerializer(data=record_data)
            if record.is_valid():
                record.save()
                car = CarSerializer(car, data=car_data)
            else:
                print(record.errors)
                return JsonResponse({"Message": "Create Record Failed"}, safe=False)
        if car.is_valid():
            car.save()
            return JsonResponse({"Message": "Success"}, safe=False)
        else:
            print(car.errors)
            return JsonResponse({"Message": "Change WorkingState Failed"}, safe=False)


@csrf_exempt
def getRepairRecords(request):
    if request.method == "GET":
        try:
            car = Car.objects.get(CarID=request.GET.get("CarID"))
            print(car.to_dict)
        except Car.DoesNotExist:
            return JsonResponse({"Message": "Car Does Not Exist"}, safe=False)
        records = Repair.objects.filter(Car=car)
        res = []
        for record in records:
            print(record.to_dict())
            res.append(record.to_dict())
        return JsonResponse({"records": res}, safe=False)


@csrf_exempt
def deleteCar(request):
    if request.method == "POST":
        try:
            #DELETE = QueryDict(request.body)
            #print(DELETE)
            car = Car.objects.get(CarID=request.POST.get("CarID"))
        except Car.DoesNotExist:
            return JsonResponse({"Message": "Car Does Not Exist"}, safe=False)
        car.delete()
        return JsonResponse({"Message": "Success"}, safe=False)
